<?php
	
	require_once (CMS_HOME_DIR . 'lib/CmsWriterDelegate.php');

	set_include_path(get_include_path() .":" . CMS_CORE . ":/usr/local/gravitate/Zend/ZendFramework-1.10.2-minimal/library");

	include_once( "fta.201003310000/fta.php");
	fta_registerModules(
		array(
		"FTAORM/FTAORM",
		"FTAORM/FTAORMCMSContentMetadata",
		"FTAORM/FTAORMCMSContent",
		"FTATag/FTATag",
		"FTAORM/FTAORMManyToManyWrapper"
		)
	);

class FTATaggingCmsWriterDelegate extends LoggingCmsWriterDelegate {
	
	public function __construct($formId,CmsDatabaseConnection $db) {
		parent::__construct ($formId, $db);
	}
		
	function didSave($documentCode){

		global $db;
		$dsninfo = DB::parseDSN($db->dsn); 
	
		$zdb = Zend_Db::factory('Pdo_Mysql', array(
		    'host'			=> $dsninfo['hostspec'],
			'username'		=> $dsninfo['username'],
			'password'		=> $dsninfo['password'],
		    'dbname'		=> $dsninfo['database'],
			'persistent'	=> false
		));
			 
		//1. load the content in via orm
		
		$content = FTAORMFullCMSContent::getObjectWithId($documentCode, $zdb); 
		$content->setTags($content->cmscontentmetadata->tags);
		$content->cmscontentmetadata->tags = implode(', ', $content->tags);
		
		try {

			$zdb->beginTransaction();
            // save tags
			$content->save();

            // save tags into searchleyowrds
            foreach ($content->tags as $documentWord) {
                if (strlen($documentWord) > 2){
                    $zdb->insert('searchkeyword', array('documentcode'=>$documentCode, 'word' => trim( $documentWord  )));
                }
            }

			$zdb->commit();

		} catch (Exception $e ) {
			// rollback.
			try {
				$zdb->rollback();
			} catch (Exception $e){}
		}		
		
	}	
	
	
	
}
